<?php
/**
 * Created by YUNYI.
 * User: james.xiao
 * Date: 2021/5/17
 * Time: 11:32
 */

namespace yy\helper;


use think\facade\Db;

/**
 * 数据表整理成文档
 * Class ShowDoc
 * @package app\units
 */
class ShowDoc
{
    protected $br = "\r\n";

    public static function init()
    {
        return new self();

    }

    /**
     * 写入文档
     */
    public function database()
    {
        $html = $this->all();
        file_put_contents('./database.md' , $html);

    }

    /**
     * 取所有表
     * @return string
     */
    public  function all()
    {
        $database = Db::getConfig('connections.mysql.database');

        $results = Db::query("show tables from `" .$database . '`');
        $html = "# 数据表结构";
        $html .= $this->br;
        $html .= $this->br;
        $html .= $this->br;
        foreach ($results as $result) {
            $html .= $this->one($result['Tables_in_'.$database]);
        }
        return $html;
    }

    /**
     * 取一个表
     * @param $table
     * @return string
     */
    public  function one($table)
    {
        $res = Db::query("show table status like '{$table}'");
        $comment = $res[0]['Comment'];
        $br = $this->br;
        $html = "#### " . $table .' ' . $comment;
        $sql = "SHOW FULL COLUMNS FROM `" . $table . '`';
        $res = Db::query($sql);
        $data = array_map(function ($v){
           $v['Comment'] = str_replace(["\r" , "\n"] , ' ' , $v['Comment']);
           $ret = [
               $v['Field' ],
               $v['Type' ],
               $v['Null' ],
               $v['Default' ],
               $v['Comment'],
           ];
           return "| " . join(" | " , $ret) . " |";
        },$res );

        $html .= $br;
        $html .= $br;
        $html .= "|字段|类型|空|默认|注释|";
        $html .= $br;
        $html .= "|:-:|:-:|:-:|:-:|:-:|";
        $html .= $br;
        $html .= join($br , $data);
        $html .= $br;
        $html .= "- 备注";
        $html .= $br;
        $html .= $br;
        $html .= "---";
        $html .= $br;
        $html .= $br;
        return $html;
    }

}